<?php
/**
 * Date: 2018/10/29
 * Time: 21:37
 */

namespace module;


use model\PolicyModel;
use think\Db;
use exception\ResponsableException;
use module\UserApi;

class InsurerApi
{

    /**
     *  根据保险人ui_id 获取保单详情
     * @param string $pId 主键id
     * @return array
     */
    public static function getInfo($pId, $uid)
    {
        $info = [];
        $info = Db::table('policy')
            ->field('policy.*,policy_item.pi_id,policy_item.goods_type,policy_item.goods_name,policy_item.goods_num,policy_item.good_price,policy_item.good_pg_price,
            policy_item.damage_at,policy_item.damage_result,policy_item.omit,policy_item.city,policy_item.classify,policy_item.address_detail,
            policy_item.other_report,policy_item.present_at,policy_item.goods_list,policy_item.goods_desc,policy_item.present_img,policy_item.present_video,policy_item.should_at,policy_item.rem_company,
            policy_item.linkman,policy_item.connect_phone,policy_item.author_report')
            ->join('policy_item', 'policy.policy_num=policy_item.policy_num', 'LEFT')
            ->where('policy.p_id', $pId)
            ->where('policy.ui_id', $uid)
            ->where('policy.delete_ts', 0)
            ->find();
        return $info;
    }

    /**
     *  根据条件获取保单详情
     * @param string $pId 主键id
     * @return array
     */
    public static function getInfoByWherePolicyItem($where, $filed = ['*'])
    {
        $info = [];
        $info = Db::table('policy_item')
            ->field($filed)
            ->where($where)
            ->where('delete_ts', 0)
            ->find();
        return $info;
    }

    /**
     *  根据保险人ui_id 获取保单详情
     * @param string $pId 主键id
     * @return array
     */
    public static function getRecordorInfo($pId, $recordor_id)
    {
        $info = [];
        $info = Db::table('policy a')
            ->field('a.p_id,a.ui_id,a.recordor_id,a.policy_num,a.report_num,a.insurance_type,a.policy_status,a.recoder_status,a.end_at,a.created_at,a.now_status,a.company_end_at')
            ->field('b.goods_type,b.goods_name,b.goods_num,b.good_price,b.good_pg_price,b.damage_at,b.damage_result,b.omit,b.city,b.classify,b.address_detail,b.other_report,b.present_at,b.goods_list,b.goods_desc,b.present_video,b.present_img,b.should_at,b.rem_company,b.linkman,b.connect_phone,b.author_report,b.created_at as lu_at,b.complete_at')
            ->join('policy_item b', 'a.policy_num=b.policy_num', 'LEFT')
            ->where('a.p_id', $pId)
            ->where('a.recordor_id', $recordor_id)
            ->where('a.delete_ts', 0)
            ->find();
        return $info;
    }

    /**
     * @param int $uid 用戶id
     * @param string $policy_num 保单号
     * @param array $policyData policy表添加信息
     * @param array $policyIetmData policy_ietm表添加信息
     * @return array
     */
    public static function insertPolicy($uid, $policy_num, $policyData, $policyIetmData)
    {

        try {
            Db::startTrans();
            $pilicyInfo = Db::table('policy')->where('ui_id', $uid)->where('policy_num', $policy_num)->find();
            if ($policyData) {
                $pilicyObject = Db::table('policy');
                if (!$pilicyInfo) {
                    $pilicyObject->insert(array_merge($policyData, ['policy_status' => 1, 'created_at' => date('Y-m-d H:i:s')]));
                } else {
                    $pilicyObject->where('policy_num', $policy_num)->update(array_merge($policyData, ['updated_at' => date('Y-m-d H:i:s')]));
                }
            }
            if ($policyIetmData) {
                $itemInfo = Db::table('policy_item')->where('policy_num', $policy_num)->find();
                $itemObject = Db::table('policy_item');
                if (!$itemInfo) {
                    $itemObject->insert(array_merge($policyIetmData, ['created_at' => date('Y-m-d H:i:s'), 'policy_num' => $policy_num]));
                } else {
                    $itemObject->where('policy_num', $policy_num)->update(array_merge($policyIetmData, ['updated_at' => date('Y-m-d H:i:s')]));
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }

    /**
     * @param int $uid 用戶id
     * @param string $policy_num 保单号
     * @param array $policyIetmData policy_ietm表添加信息
     * @return array
     */
    public static function insertItemPolicy($uid, $policy_num, $now_status, $policyIetmData)
    {

        try {

            $pilicyInfo = Db::table('policy')->where('recordor_id', $uid)->where('policy_num', $policy_num)->find();
            if (!$pilicyInfo) {
                throw new ResponsableException('没有保单前置信息');
            }
            Db::startTrans();
            if ($policyIetmData) {
                $itemInfo = Db::table('policy_item')->where('policy_num', $policy_num)->find();
                $itemObject = Db::table('policy_item');
                if (!$itemInfo) {
                    $itemObject->insert(array_merge($policyIetmData, ['created_at' => date('Y-m-d H:i:s'), 'policy_num' => $policy_num]));
                } else {
                    $itemObject->where('policy_num', $policy_num)->update(array_merge($policyIetmData, ['updated_at' => date('Y-m-d H:i:s')]));
                }
                //修改成待录人未提交状态
                Db::table('policy')->where('recordor_id', $uid)->where('policy_num', $policy_num)->update(['updated_at' => date('Y-m-d H:i:s'), 'now_stauts' => $now_status, 'recoder_status' => 1]);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }

    /**
     * @param int $uid 用戶id
     * @param string $policy_num 保单号
     * @param array $policyIetmData policy_ietm表添加信息
     * @return array
     */
    public static function updateItemPolicy($uid, $policy_num, $policyIetmData)
    {

        try {

            $pilicyInfo = Db::table('policy')->where('recordor_id', $uid)->where('policy_num', $policy_num)->find();
            if (!$pilicyInfo) {
                throw new ResponsableException('没有保单前置信息');
            }
            $itemInfo = Db::table('policy_item')->where('policy_num', $policy_num)->find();
            if (!$itemInfo) {
                throw new ResponsableException('信息不存在');
            }
            Db::startTrans();
            if ($policyIetmData) {
                $itemObject = Db::table('policy_item');
                $itemObject->where('policy_num', $policy_num)->update(array_merge($policyIetmData, ['updated_at' => date('Y-m-d H:i:s')]));
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }

    /**
     * @param int $uid 用戶id
     * @param string $policy_num 保单号
     * @param array $policyIetmData policy_ietm表添加信息
     * @return array
     */
    public static function updateByPolicy($uid, $policy_num, $policyIetmData)
    {

        try {

            $pilicyInfo = Db::table('policy')->where('ui_id', $uid)->where('policy_num', $policy_num)->find();
            if (!$pilicyInfo) {
                throw new ResponsableException('没有保单前置信息');
            }
            $itemInfo = Db::table('policy_item')->where('policy_num', $policy_num)->find();
            if (!$itemInfo) {
                throw new ResponsableException('信息不存在');
            }
            Db::startTrans();
            if ($policyIetmData) {
                $itemObject = Db::table('policy_item');
                $itemObject->where('policy_num', $policy_num)->update(array_merge($policyIetmData, ['updated_at' => date('Y-m-d H:i:s')]));

            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }

    /**
     * 代录人添加主表
     * @param array $policyData policy表添加信息
     * @return array
     */
    public static function insertOtherPolicy($policyData)
    {

        return Db::table('policy')->insert($policyData);

    }

    /**
     * 保单列表
     * @param int $uid 用户id
     * @return array
     */
    public static function getList($uid, $policy_num,  $type)
    {
        $where['ui_id'] = $uid;
        if ($policy_num) {
            $where['policy_num'] = ['like','%'.$policy_num.'%'];
        }
        if ($type>=0) {
            $where['policy_status'] = $type;
        }

        $list = [];
        $statusArr = [0 => '驳回修改', 1 => '未递交审核', 2 => '代录人未递交', 3 => '代录资料未确认', 4 => '待审核', 5 => '被保险人未确认', 6 => '被保险人未委托', 7 => '全部资料已完成', 8 => '拍卖已完成'];
        $list = Db::table('policy')->field('p_id,policy_num,report_num,policy_status,created_at,end_at')->where($where)->order('policy_status desc')->select();
        if (!$list) {
            return $list;
        }
        foreach ($list as $k => $v) {

            $list[$k]['status_str'] = isset($statusArr[$v['policy_status']]) ? $statusArr[$v['policy_status']] : '';
        }
        return $list;

    }

    /**
     * 代录人待录列表
     * @param int $recordor_id 我的dai待录
     * @return array
     */
    public static function getByme($recordor_id)
    {
        $list = [];
        //查找选择代录人状态
        $list = Db::table('policy')->field('p_id,ui_id,policy_num,report_num,recoder_status,created_at,end_at')->where('recordor_id', $recordor_id)
            ->where('policy_status', PolicyModel::POLICY_RECORDOR_NOT_USED_STATUS)
            ->where('recoder_status', 0)
            ->select();

        if (!$list) {
            return $list;
        }
        $statusArr = [0 => '未录入', 1 => '未递交', 2 => '已提交保险公司人员未确认', 3 => '驳回', 4 => '已完成'];
        foreach ($list as $k => $v) {
            $bao_info = Db::table('user_info')->where('ui_id', $v['ui_id'])->find();
            $list[$k]['recoder_str'] = isset($statusArr[$v['recoder_status']]) ? $statusArr[$v['recoder_status']] : '';
            $list[$k]['company_name'] = !empty($bao_info['company_name']) ? $bao_info['company_name'] : '';
        }

        return $list;

    }

    /**
     * 待录人历史资料
     * @param int $recordor_id 我的dai待录
     * @return array
     */
    public static function alreadyList($recordor_id, $type='',$policy_num='')
    {
        $list = [];
        $where = [];
        if ($type >=0 ) {
            $where['recoder_status'] = $type;
        }
        if($policy_num){
            $where['policy_num'] = ['like','%'.$policy_num.'%'];
        }
        //查找选择代录人状态
        $list = Db::table('policy')->field('p_id,ui_id,policy_num,report_num,recoder_status,created_at,end_at')->where('recordor_id', $recordor_id)
            ->where('policy_status', 'in', [PolicyModel::POLICY_RECORDOR_NOT_USED_STATUS, PolicyModel::POLICY_REVISE_STATUS, PolicyModel::POLICY_ECORDO_NOT_CONFITM_STATUS, PolicyModel::POLICY_CHECK_PENDING_STATUS])
            ->where('recoder_status', '>', 0)
            ->where($where)
            ->select();

        if (!$list) {
            return $list;
        }
        $statusArr = [0 => '未录入', 1 => '未递交', 2 => '已提交保险公司人员未确认', 3 => '驳回', 4 => '已完成'];
        foreach ($list as $k => $v) {
            $bao_info = Db::table('user_info')->where('ui_id', $v['ui_id'])->find();
            $list[$k]['recoder_str'] = isset($statusArr[$v['recoder_status']]) ? $statusArr[$v['recoder_status']] : '';
            $list[$k]['company_name'] = !empty($bao_info['company_name']) ? $bao_info['company_name'] : '';
        }

        return $list;

    }

    /**
     * 更改表
     * @param array $where
     * @param array $update
     * @return boolean
     */
    public static function updatePolicy($where, $update)
    {
        return Db::table('policy')->where($where)->update($update);

    }

    /**
     * 查找
     * @param array $where
     * @return array[]
     */
    public static function getPolicyInfo($filed = ['*'], $where)
    {
        $info = Db::table('policy')->field($filed)->where($where)->find();
        return $info ? $info : [];
    }

    /**
     * 根据被保险人查找保险员信息
     * @param array $where
     * @return array[]
     */
    public static function getUserbyRemerId($remer_id)
    {
        //查找当前的跟被保险人关联的保单
        $info = self::getPolicyInfo(['ui_id'], ['remer_id' => $remer_id, 'delete_ts' => 0]);
        $user_info = UserApi::getUserInfoByUid($info['ui_id']);
        return $user_info;
    }

    /**
     * 业务员驳回  保险人员驳回
     * @param int $p_id
     * @param int $data 接收数据
     * @return array[]
     */
    public static function reject($uid, $p_id, $data)
    {
        //  0,驳回修改 ，1未递交审核 2代录人未递交 3代录资料未确认 4待审核 5被保险人未确认 6被保险人未委托 7 全部资料已完成 8 拍卖已完成
        try {
            Db::startTrans();
            $pilicyInfo = Db::table('policy')
                ->where('p_id', $p_id)
                ->where('delete_ts', 0)
                ->where('policy_status', PolicyModel::POLICY_ECORDO_NOT_CONFITM_STATUS)
                ->find();
            if (!$pilicyInfo) {
                throw new ResponsableException('保单信息不存在');
            }
            $return_info = Db::table('return_policy')
                ->where('p_id', $p_id)
                ->where('extend_table', 'user_info')
                ->where('extend_id', $uid)
                ->where('status',1)
                ->find();
            if ($return_info) {
                Db::commit();
                throw new ResponsableException('请不要重复驳回');
            }
            $data = array_merge($data, ['created_at' => date('Y-m-d H:i:s'), 'p_id' => $p_id, 'extend_table' => 'user_info', 'extend_id' => $uid]);
            Db::table('return_policy')->insert($data);
            //修改保单状态
            $update['policy_status'] = PolicyModel::POLICY_RECORDOR_NOT_USED_STATUS;//主状态修改成驳回状态
            $update['updated_at'] = date('Y-m-d H:i:s');
            if ($pilicyInfo['recordor_id'] > 0) {
                $update['recoder_status'] = 3;//代录人修改成驳回状态
            }
            self::updatePolicy(['p_id' => $p_id], $update);


            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }


    }

    /**
     * 获取驳回信息
     * @param int $uid 保单id
     * @return array[]
     */
    public static function getRetuenList($p_id)
    {

        $data['policy_return'] = [];
        $data['goods_return'] = [];
        $data['under_return'] = [];
        $data['situation_return'] = [];
        $data['info_return'] = [];
        $data['certificate_return'] = [];
        $list = Db::table('return_policy')
            ->where('p_id', $p_id)
            ->where('status', 1)
            ->select();

        if (!$list) return $data;

        foreach ($list as $v) {
            if (!$v) continue;
            //保单险种驳回信息
            if ($v['policy_return']) {
                array_push($data['policy_return'], $v['policy_return']);
            }
            //货品信息驳回信息
            if ($v['goods_return']) {
                array_push($data['goods_return'], $v['goods_return']);
            }
            //货品受损驳回信息
            if ($v['under_return']) {
                array_push($data['under_return'], $v['under_return']);
            }
            //货品现状驳回信息
            if ($v['situation_return']) {
                array_push($data['situation_return'], $v['situation_return']);
            }
            //物权信息驳回信息
            if ($v['info_return']) {
                array_push($data['info_return'], $v['info_return']);
            }
            //授权书驳回信息
            if ($v['certificate_return']) {
                array_push($data['certificate_return'], $v['certificate_return']);
            }

        }
        return $data;

    }

    public static function confirmSubmit($uid, $policy_num, $now_status, $author_report = '')
    {
        try {

            Db::startTrans();
            $pilicyInfo = Db::table('policy')
                ->where('policy_num', $policy_num)
                ->where('ui_id', $uid)
                ->where('delete_ts', 0)
                ->find();

            if (!$pilicyInfo) {
                Db::commit();
                throw new ResponsableException('保单不存在');
            }
            if ($pilicyInfo['policy_status'] == PolicyModel::POLICY_CHECK_PENDING_STATUS) {
                throw new ResponsableException('请不要重复提交');
            }
            $itemInfo = Db::table('policy_item')
                ->where('policy_num', $policy_num)
                ->where('delete_ts', 0)
                ->find();
            if (!$itemInfo) {
                Db::commit();
                throw new ResponsableException('请输入其他信息');
            }
            //生成被保险人用户信息
            $userInset['role_id'] = 3;
            $userInset['username'] = $itemInfo['linkman'];
            $userInset['head_img'] = config('head_img');
            $userInset['mobile'] = $itemInfo['connect_phone'];
            $userInset['company_name'] = $itemInfo['rem_company'];
            $userInset['created_at'] = date('Y-m-d H:i:s');
            $user_info = Db::table('user_info')->where('mobile', $itemInfo['connect_phone'])->find();
            if ($user_info) {
                $id = $user_info['ui_id'];
                //并且更新新数据
                Db::table('user_info')->where('ui_id',$id)->update(['username'=>$itemInfo['linkman'],'company_name'=>$itemInfo['rem_company'],'updated_at'=> date('Y-m-d H:i:s')]);
            } else {
                $id = Db::table('user_info')->insertGetId($userInset);
            }
            $updateArr['now_status'] = $now_status;
            $updateArr['remer_id'] = $id;
            $updateArr['updated_at'] = date('Y-m-d H:i:s');
            $updateArr['policy_status'] = PolicyModel::POLICY_CHECK_PENDING_STATUS;//修改提交审核状态
            if ($pilicyInfo['recordor_id'] > 0) {  //如果是代录人录入 修改代录人状态为4
                $updateArr['recoder_status'] = 2;//保持原状态  等待审核通过才改完4 已完成
            }
            Db::table('policy')->where('policy_num', $policy_num)->update($updateArr);
            $itemUpdateArr['complete_at'] = date('Y-m-d H:i:s');
            $itemUpdateArr['updated_at'] = date('Y-m-d H:i:s');
            if ($author_report) {
                $itemUpdateArr['author_report'] = $author_report;
            }
            Db::table('policy_item')->where('policy_num', $policy_num)->update($itemUpdateArr);
            //有之前驳回信息  置为通过
            if (Db::table('return_policy')->where('p_id', $pilicyInfo['p_id'])->where('extend_table', 'user_info')->where('extend_id', $pilicyInfo['ui_id'])->find()) {
                Db::table('return_policy')->where('p_id', $pilicyInfo['p_id'])->where('extend_table', 'user_info')->where('extend_id', $pilicyInfo['ui_id'])->update(['status' => 2]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }

      //修改完提交

    public static function confirmSubmitUpdate($uid, $policy_num, $now_status, $policy_item_data)
    {
        try {

            Db::startTrans();
            $pilicyInfo = Db::table('policy')
                ->where('policy_num', $policy_num)
                ->where('ui_id', $uid)
                ->where('delete_ts', 0)
                ->find();
            if (!$pilicyInfo) {
                Db::commit();
                throw new ResponsableException('保单不存在');
            }
            if ($pilicyInfo['policy_status'] == PolicyModel::POLICY_CHECK_PENDING_STATUS) {
                throw new ResponsableException('请不要重复提交');
            }
            $itemInfo = Db::table('policy_item')
                ->where('policy_num', $policy_num)
                ->where('delete_ts', 0)
                ->find();
            //没有附表信息  插入
            if (!$itemInfo) {
                Db::table('policy_item')->insert(array_merge(['policy_num'=>$policy_num],$policy_item_data));
            }else{
                Db::table('policy_item')
                    ->where('policy_num', $policy_num)
                    ->where('delete_ts', 0)
                    ->update($policy_item_data);
            }
            //被保险人信息是否更改
            $userInset['role_id'] = 3;
            $userInset['username'] = $policy_item_data['linkman'];
            $userInset['head_img'] = config('head_img');
            $userInset['mobile'] = $policy_item_data['connect_phone'];
            $userInset['company_name'] = $policy_item_data['rem_company'];
            $userInset['created_at'] = date('Y-m-d H:i:s');
            $user_info = Db::table('user_info')->where('mobile', $itemInfo['connect_phone'])->find();
            if ($user_info) {
                $id = $user_info['ui_id'];
            } else {
                $id = Db::table('user_info')->insertGetId($userInset);
            }
            $updateArr['now_status'] = $now_status;
            $updateArr['remer_id'] = $id;
            $updateArr['updated_at'] = date('Y-m-d H:i:s');
            $updateArr['policy_status'] = PolicyModel::POLICY_CHECK_PENDING_STATUS;//修改提交审核状态
            if ($pilicyInfo['recordor_id'] > 0) {  //如果是代录人录入 修改代录人状态为4
                $updateArr['recoder_status'] = 4;//修改提交审核状态
            }
            Db::table('policy')->where('policy_num', $policy_num)->update($updateArr);
            $itemUpdateArr['complete_at'] = date('Y-m-d H:i:s');
            $itemUpdateArr['updated_at'] = date('Y-m-d H:i:s');
            //有之前驳回信息  置为通过
            if (Db::table('return_policy')->where('p_id', $pilicyInfo['p_id'])->where('extend_table', 'user_info')->where('extend_id', $pilicyInfo['ui_id'])->find()) {
                Db::table('return_policy')->where('p_id', $pilicyInfo['p_id'])->where('extend_table', 'user_info')->where('extend_id', $pilicyInfo['ui_id'])->update(['status' => 2]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage());
        }

    }


}